package models

// websocket数据结构.
import (
	"container/list"
)

// EventType 事件类型
type EventType int64

//事件类型常数
const (
	EVENT_JOIN     = "EVENT_JOIN"     //事件类型建立连接
	EVENT_LEAVE    = "EVENT_LEAVE"    //事件类型断开连接
	EVENT_MESSAGE  = "EVENT_MESSAGE"  //事件类型消息
	WELCOM_MESSAGE = "WELCOM_MESSAGE" //事件类型消息欢迎词
)

//WsEvent 事件结构
type WsEvent struct {
	Type        string        `json:"cmd"` //类型 JOIN, LEAVE, MESSAGE
	UserName    string        `json:"username,omitempty"`
	UserId      string        `json:"userid,omitempty"`
	TargetId    string        `json:"targetid,omitempty"`
	RoomId      string        `json:"roomid,omitempty"`
	TimeStamp   int           `json:"timestamp,omitempty"` // Unix timestamp (secs)
	Content     string        `json:"msg,omitempty"`
	OnlineUsers []interface{} `json:"onlineUsers,omitempty"`
}

const archiveSize = 20

//事件档案。
var archive = list.New()

// NewArchive 将新事件保存到归档列表。
func NewArchive(event WsEvent) {
	if archive.Len() >= archiveSize {
		archive.Remove(archive.Front())
	}
	archive.PushBack(event)
}

// GetEvents 返回lastReceived之后的所有事件。
func GetEvents(lastReceived int64) []WsEvent {
	events := make([]WsEvent, 0, archive.Len())
	for event := archive.Front(); event != nil; event = event.Next() {
		e := event.Value.(WsEvent)
		if e.TimeStamp > int(lastReceived) {
			events = append(events, e)
		}
	}
	return events
}
